package org.example.ipersistent.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.example.ipersistent.pojo.Configuration;
import org.example.ipersistent.pojo.MappedStatement;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuilder {
  private Configuration configuration;

  public XmlMapperBuilder(Configuration configuration) {
    this.configuration = configuration;
  }

  public void parse(InputStream inputStream) throws DocumentException {
    Document document = new SAXReader().read(inputStream);
    Element root = document.getRootElement();
    String namespace = root.attributeValue("namespace");
    // select
    List<Element> selectList = root.selectNodes("//select");
    for (Element select : selectList) {
      String id = select.attributeValue("id");
      String resultType = select.attributeValue("resultType");
      String paramType = select.attributeValue("paramType");
      String sql = select.getTextTrim();
      MappedStatement mappedStatement = new MappedStatement();
      String statementId = namespace + ":" + id;
      mappedStatement.setStatementId(statementId);
      mappedStatement.setResultType(resultType);
      mappedStatement.setParamType(paramType);
      mappedStatement.setSql(sql);
      mappedStatement.setCommandType("select");
      configuration.getMappedStatementMap().put(statementId, mappedStatement);
    }
    // insert update delete
  }
}
